<template>
  <div>
    <!-- 提示框 -->
    <el-alert :title="goodId===0? '添加商品信息':'修改商品信息'" type="info" :closable="false" center show-icon>
    </el-alert>
    <!-- 步骤条 -->
    <el-steps align-center :active="active - 0" finish-status="success">
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <!-- tab页 -->

    <el-tabs :before-leave="beforeTabLeave" v-model="active" @tab-click="tabClicked" :tab-position="'left'" style="height:400px;overflow-y:auto">
      <el-tab-pane name="0" label="基本信息">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model.trim="addForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input type="number" v-model.trim="addForm.goods_price"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input type="number" v-model.trim="addForm.goods_weight"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input type="number" v-model.trim="addForm.goods_number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <!-- 选择器 -->
            <el-cascader clearable v-model="addForm.goods_cat" :options="cateList" :props="{ expandTrigger: 'hover',value:'cat_id',label:'cat_name' }" @change="handleChange"></el-cascader>

          </el-form-item>
        </el-form>
      </el-tab-pane>
      <!-- 商品参数 -->
      <el-tab-pane name="1" label="商品参数">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormOneRef" label-width="100px" label-position="top">
          <el-form-item v-for="item in manyTableDate" :key="item.attr_id" :label="item.attr_name">
            <!-- 复选框 -->
            <el-checkbox :indeterminate="item.isIndeterminate" v-model="item.checkAll" @change="handleCheckAllChange($event,item)">全选</el-checkbox>

            <el-checkbox-group v-model="item.checkList" @change="handleCheckedCitiesChange($event,item)">
              <el-checkbox border v-for="val,idx in item.attr_vals" :key="idx" :label="val"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <!-- 商品属性 -->
      <el-tab-pane name="2" label="商品属性">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormTwoRef" label-width="100px" label-position="top">
          <el-form-item :key="item.id" v-for="item in onlyTableDate" :label="item.attr_name">
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <!-- 图片上传 -->
      <el-tab-pane name="3" label="商品图片">
        <el-upload :file-list="fileList" :headers="header" :action="uploadImgUrl" :on-preview="imgHandlePreview" :before-remove="imgHandleRemove" :on-success="imgHandleSuccess" list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-tab-pane>
      <el-tab-pane name="4" label="商品内容">
        <quill-editor v-model="addForm.goods_introduce"></quill-editor>
        <el-button @click="addGood" class="addGoodsBut" type="primary">{{goodId===0? '添加商品':'修改商品'}}</el-button>
      </el-tab-pane>

    </el-tabs>
    <!-- 图片显示 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="30%">
      <img style="width:100%" :src="previewUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request.js'
import _ from 'lodash'
export default {
  name: 'goodAdd',
  data() {
    return {
      goodId: 0,
      active: '0',
      cateList: [],
      passCheck: true,
      fileList: [],
      header: { Authorization: localStorage.getItem('token') },
      addForm: {
        goods_name: '',
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      addFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品属性', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品图片', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品内容', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品类型', trigger: 'blur' }]
      },
      // 动态参数列表
      manyTableDate: [],
      // 多选框选中
      checkList: [],
      // 静态属性列表
      onlyTableDate: [],
      uploadImgUrl: request.defaults.baseURL + '/upload',
      // 当前图片地址
      previewUrl: '',
      // 是否显示对话框
      previewVisible: false
    }
  },
  methods: {
    // 获取商品分类
    async getCateList() {
      const { data: res } = await this.$api.goods.getCatesApi()
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
      console.log(this.cateList)
    },
    // 当选择器发生改变时
    handleChange(value) {
      this.onlyTableDate = []
      this.manyTableDate = []
      if (value.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 当标签页切换时
    beforeTabLeave(newTab, oldTab) {
      if (oldTab === '0') {
        this.$refs.addFormRef.validate(valid => {
          if (!valid) return (this.passCheck = false)
          this.passCheck = true
        })
      }
      if (!this.passCheck) this.$message.error('请完成必填项')
      return this.passCheck
    },
    // 当点击标签栏时
    async tabClicked() {
      console.log(this.manyTableDate.length)
      if (this.active === '1' && this.manyTableDate.length === 0) {
        // 获取动态参数列表
        const { data: res } = await this.$api.goods.getAttributesApi(this.cateId, 'many')
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        res.data.forEach(item => {
          console.log(item)
          // 是否全选
          item.checkAll = false
          // 是否半选
          item.isIndeterminate = false
          // 选中列表
          item.checkList = []
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
          // 如果goodId不为0说明正在修改
          if (this.goodId !== 0) {
            this.addForm.attrs.forEach(item2 => {
              if (item2.attr_sel === 'many' && item2.attr_id === item.attr_id) {
                item.checkList = item2.attr_value.split(' ')
                // 如果选中数量等于最大数量就全选
                if (item.checkList.length === item.attr_vals.length) {
                  item.checkAll = true
                } else if (item.checkList.length <= item.attr_vals.length && item.checkList.length !== 0) {
                  item.isIndeterminate = true
                }
              }
            })
          }
        })

        this.manyTableDate = res.data
        console.log(this.manyTableDate)
      } else if (this.active === '2' && this.onlyTableDate.length === 0) {
        // 获取静态属性列表
        const { data: res } = await this.$api.goods.getAttributesApi(this.cateId, 'only')
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        res.data.forEach(item => {
          // 如果goodId不为0说明正在修改
          if (this.goodId !== 0) {
            this.addForm.attrs.forEach(item2 => {
              if (item2.attr_sel === 'only' && item2.attr_id === item.attr_id) {
                item.attr_vals = item2.attr_value
              }
            })
          }
        })
        this.onlyTableDate = res.data
        console.log(this.onlyTableDate)
      }
    },
    // 点击全选按钮要做的操作
    handleCheckAllChange(val, item) {
      // console.log(val, item)
      // 如果选中了全选按钮 把列表所有参数赋值给列表
      item.checkList = !val ? [] : item.attr_vals
      // 修改半选状态为false
      item.isIndeterminate = false
      console.log(this.manyTableDate)
    },
    // 选中每一项时的操作
    handleCheckedCitiesChange(val, item) {
      console.log(item.checkList)
      // 选中的长度
      const checkedCount = val.length
      // 长度不等于参数列表的长度就取消勾选复选框
      item.checkAll = checkedCount === item.attr_vals.length
      console.log(val)
      // 长度小于参数列表，且大于0时显示半选
      item.isIndeterminate = checkedCount > 0 && checkedCount < item.attr_vals.length
    },
    // 点击图片显示文本框
    imgHandlePreview(file) {
      // 获取图片url地址
      if (file.response) {
        this.previewUrl = file.response.data.url
      } else {
        this.previewUrl = file.url
      }

      this.previewVisible = true
    },
    // 移除
    imgHandleRemove(file) {
      let path = ''
      // 获取要移除图片的路径
      if (file.response) {
        path = file.response.data.tmp_path
      } else {
        path = '/tmp_uploads/' + file.name
      }
      console.log(path)
      // 从数组中找到索引值
      const i = this.addForm.pics.findIndex(x => x.pic === path)

      // 移除
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm.pics)
    },
    sleep(n) {
      const start = new Date().getTime()
      //  console.log('休眠前：' + start);
      while (true) {
        if (new Date().getTime() - start > n) {
          break
        }
      }
      // console.log('休眠后：' + new Date().getTime());
    },
    // 上传成功后
    imgHandleSuccess(response) {
      const picInfo = { pic: '/' + response.data.tmp_path.replaceAll('\\', '/') }
      this.addForm.pics.push(picInfo)
      console.log(this.addForm.pics)
    },
    async addGood() {
      // 使用lodash中的方法进行深拷贝
      const form = _.cloneDeep(this.addForm)
      // 将分类数组拼接为字符串
      form.goods_cat = form.goods_cat.join(',')
      // 深拷贝动态参数和静态属性
      const manyTableDate = _.cloneDeep(this.manyTableDate)
      const onlyTableDate = _.cloneDeep(this.onlyTableDate)
      form.attrs = []
      // 以规定结构push到总的表单中
      manyTableDate.forEach(item => {
        const attrInfo = {
          attr_id: item.attr_id,
          attr_value: item.checkList.join(' ')
        }
        if (attrInfo.attr_value.length !== 0) form.attrs.push(attrInfo)
      })
      onlyTableDate.forEach(item => {
        const attrInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
        form.attrs.push(attrInfo)
      })
      console.log(form)
      if (this.goodId !== 0) {
        // 发送添加商品请求
        const { data: res } = await this.$api.goods.putGoodsApi(this.goodId, form)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('修改成功')
        this.$router.push('/home/goods')
        return
      }
      // 发送添加商品请求
      const { data: res } = await this.$api.goods.postGoodsApi(form)
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      this.$message.success('添加成功')
      this.$router.push('/home/goods')
    },
    async getGoodDesc() {
      const { data: res } = await this.$api.goods.getGoodById(this.goodId)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      const goodsCat = res.data.goods_cat.split(',')
      const pic = []
      res.data.pics.forEach(item => {
        pic.push({
          pic: '/tmp_uploads/' + item.pics_big.split('/')[3].replaceAll('big_', '')
        })
        this.fileList.push({
          name: item.pics_big.split('/')[3].replaceAll('big_', ''),
          url: item.pics_big_url
        })
      })
      this.addForm = {
        goods_name: res.data.goods_name,
        goods_cat: goodsCat,
        goods_price: res.data.goods_price,
        goods_number: res.data.goods_number,
        goods_weight: res.data.goods_weight,
        goods_introduce: res.data.goods_introduce,
        pics: pic,
        attrs: res.data.attrs
      }
      console.log(this.addForm.goods_cat)
    },
    putChange() {}
  },
  created() {
    this.getCateList()
    if (this.$route.query.goods_id) {
      this.goodId = this.$route.query.goods_id
      this.getGoodDesc()
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) return this.addForm.goods_cat[2]
      return null
    }
  }
}
</script>
<style lang="less" scoped>
.el-steps {
  margin: 15px 50px;
}
/deep/ .el-step__title {
  font-size: 13px;
}
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
/deep/ .ql-container {
  min-height: 300px;
}
.addGoodsBut {
  margin-top: 15px;
}
</style>
